package com.example.controller;

import com.example.entity.BsPartner;
import com.example.entity.LogonRecord;
import com.example.entity.User;
import com.example.repository.LogonRecordRepository;
import com.example.service.BsPartnerService;
import com.example.service.UserService;
import com.example.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/user")
@RestController
public class UserController {
    private Logger log = LoggerFactory.getLogger(UserController.class);

    private static EhcacheUtil ehcacheUtil = EhcacheUtil.getInstance();
    @Autowired
    private UserService userService;
    @Autowired
    private BsPartnerService bsPartnerService;
    @Autowired
    private LogonRecordRepository logonRecordRepository;

    /**
     * 合作商登录接口
     *
     * @param partnerName
     * @param partnerPassword
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Map<String, String> login(@RequestParam("partnerName") String partnerName, @RequestParam("partnerPassword") String partnerPassword, HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        User user = userService.findByuserName(partnerName);
        //判断用户是否存在
        if (user != null) {
            //判断密码是否正确
            try {
                //解密密码
               partnerPassword = RSAUtils.decryptByPrivateKey(partnerPassword);
            } catch (Exception e) {
                log.error("---------------------密码解密出现异常-----------------------");
                map.put("code", "0");
                map.put("msg", "系统异常，请稍后再试");
                return map;
            }
            partnerPassword = MD54ZHB.GetMD5Code(partnerPassword);
            if (user.getPartnerPassword().equals(partnerPassword)) {
                //生成唯一校验id，后期所有接口请求需要带上次id   用于判断用户的登录状态
                String validateId = UUID.randomUUID().toString().trim().replaceAll("-", "");
                ehcacheUtil.put("session", validateId, user);
                map.put("validateId", validateId);
                map.put("partnerId", user.getBsPartner().getId().toString());
                map.put("code", "1");
                map.put("msg", "登录成功");
                //记录用户登录记录
                LogonRecord logonRecord = new LogonRecord();
                logonRecord.setLogonTime(new Date());
                logonRecord.setPartnerId(user.getBsPartner().getId());
                logonRecord.setLogonIp(Tools.getIpAddr(request));
                logonRecordRepository.save(logonRecord);
            } else {
                map.put("code", "0");
                map.put("msg", "密码错误");
            }
        } else {
            map.put("code", "0");
            map.put("msg", "该用户不存在");
        }
        return map;
    }

    @PostMapping("/userList")
    public Map<String, Object> userList(@RequestParam("partnerId") String partnerId, @RequestParam(name = "page", required = true) Integer page,
                                        @RequestParam(name = "size") Integer size) {
        Map<String, Object> map = new HashMap<>();
        QueryParams queryParams = new QueryParams();
        queryParams.clearAll().and(Filter.eq("t2.id", partnerId)).orderDESC("register_time");
        PageRequest pageRequest = new PageRequest(page, size);
        try {
            map = userService.getUserList(queryParams, pageRequest);
            map.put("code", "1");
        } catch (Exception e) {
            map.put("code", "0");
            map.put("msg", "数据获取异常");
        }
        return map;
    }

    /**
     * 合作商信息获取
     *
     * @return
     */
    @PostMapping("/findByPartnerId")
    public Map<String, Object> findByPartnerId(@RequestParam("partnerId") Integer partnerId) {
        Map<String, Object> map = new HashMap<>();
        BsPartner bsPartner = null;
        try {
            bsPartner = bsPartnerService.findByPartnerId(partnerId);
            map.put("data", bsPartner);
            map.put("code", "1");
        } catch (Exception e) {
            map.put("code", "0");
        }
        return map;
    }

    //退出登录
    @PostMapping("/logout")
    public Map logout(@RequestParam(name = "validateId") String validateId) {
        Map<String, String> map = new HashMap<>();
        User user = (User) ehcacheUtil.get("session", validateId);
        if (user == null) {
            map.put("code", "1");
        } else {
            ehcacheUtil.remove("session", validateId);
            map.put("code", "1");
            map.put("msg", "您已成功退出系统。");
        }
        return map;
    }

    /**
     * 修改密码
     *
     * @return
     */
    @PostMapping("/editPassword")
    public Map editPassword(@RequestParam(name = "validateId") String validateId, @RequestParam(name = "password") String password) {
        Map<String, String> map = new HashMap<>();
        User user = (User) ehcacheUtil.get("session", validateId);
        if (user != null) {
            try {
                password = RSAUtils.decryptByPrivateKey(password);
                user.setPartnerPassword(MD54ZHB.GetMD5Code(password));
                user = userService.editPassword(user);
                ehcacheUtil.put("session", validateId, user);
                map.put("code", "1");
            } catch (Exception e) {
                e.printStackTrace();
                map.put("code", "0");
                map.put("msg", "系统异常");
            }
        } else {
            map.put("code", "0");
            map.put("msg", "系统异常");
        }
        return map;
    }

}
